﻿using System;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Description;

namespace PicServer.Services
{
    public static class PicServiceHost
    {
        /// <summary>
        /// 宿主对象
        /// </summary>
        private static ServiceHost host = null;


        public static void Stop()
        {
            if (host != null && host.State != CommunicationState.Closing && host.State != CommunicationState.Closed)
                host.Close();
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        public static void Start(String serviceUrl, String picServerWebUri)
        {
            if (host == null)
            {
                Uri serviceUri = new Uri(serviceUrl);
                host = new ServiceHost(typeof(PicService), serviceUri);
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                //允许从http获取数据
                behavior.HttpGetEnabled = true;
                behavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(behavior);
                host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
                    MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

                //支持程序访问的终结点
                //支持20M
                WSHttpBinding wsBinding = new WSHttpBinding();
                wsBinding.MaxReceivedMessageSize = 1024 * 1024 * 20; //字节为单位
                wsBinding.ReaderQuotas.MaxArrayLength = 1024 * 1024 * 20;
                host.AddServiceEndpoint(typeof(IPicService), wsBinding, serviceUri);
                host.Open();

                //支持weburl访问的终结点
                WebServiceHost webHost = new WebServiceHost(typeof(PicWebService), new Uri(picServerWebUri));
                WebHttpBinding webBinding = new WebHttpBinding();
                webBinding.ReaderQuotas.MaxArrayLength = 1024 * 1024 * 20;
                webHost.AddServiceEndpoint(typeof(IPicWebService), webBinding, picServerWebUri);
                webHost.Open();
            }
            else if (host.State != CommunicationState.Opening || host.State != CommunicationState.Opened)
                host.Open();
        }
    }
}
